package com.example.papermanagemant.service;

import com.example.papermanagemant.model.Paper;
import com.example.papermanagemant.repository.PaperRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PaperService {

    @Autowired
    private PaperRepository paperRepository;

    public List<Paper> findAll() {
        return paperRepository.findAll();
    }

    public Paper save(Paper paper) {
        return paperRepository.save(paper);
    }

    public void delete(Long id) {
        paperRepository.deleteById(id);
    }

    // 获取总论文数
    public long getPaperCount() {
        return paperRepository.count();
    }

    public String getAllKeywords() {
        List<Paper> papers = paperRepository.findAll();
        StringBuilder keywords = new StringBuilder();
        for (Paper paper : papers) {
            if (paper.getKeywords() != null && !paper.getKeywords().isEmpty()) {
                // 去除换行符和多余空格
                String cleanedKeywords = paper.getKeywords().replaceAll("\n", "").replaceAll("\\s+", " ").trim();
                keywords.append(cleanedKeywords).append(",");
            }
        }
        return keywords.toString();
    }

    // 根据作者、标题、关键词进行搜索
    public List<Paper> searchPapers(String search) {
        return paperRepository.findByAuthorContainingOrTitleContainingOrKeywordsContaining(search, search, search);
    }
}
